-- building_event
-- Created by chengb Jul/10/2015
-- 成就：完成建筑事件

-- 内部函数声明
local checkCondition;
local whenBuildingEventDone;

-- 注册玩家完成建筑事件的回调
EventMgr.register("achievements/building_event", event.BUILDING_EVENT_DONE, function(args)
    whenBuildingEventDone(args);
end);

-- 注册玩家完成建筑事件的回调
whenBuildingEventDone = function(args)
    local pos   = args.pos;
    local grid = DungeonM.getGridByPos(pos);
    if not grid then
        -- 格子不存在？
        return;
    end

    -- 获取当前所在的迷宫编号
    local dungeonId = DungeonM.getDungeonId();

    -- 遍历所有的子规则
    local ids = AchievementM.getIdsByRule("building_event");

    -- 判断是否是符合要求的成就
    local function isValidId(id)
        if true == AchievementM.isCompleted(id) then
            -- 已经完成了
            return false;
        end

        if not AchievementM.isBelongTo(id, dungeonId) then
            -- 不是该迷宫的成就
            return false;
        end

        -- 判断是否是需求的建筑
        local config = AchievementM.query(id);
        local ruleArg = config["rule_arg"];
        if type(ruleArg) == 'table' then
            if type(ruleArg["grid_type"]) == 'number' and
                ruleArg["grid_type"] ~= grid.type then
                return false;
            end
            
            if type(ruleArg["class"]) == 'number' and 
                ruleArg["class"] ~= grid.class then
                return false;
            end
            
            -- 如果配置了条件，还有额外检查
            if type(ruleArg["condition"] == 'string') then
                if not checkCondition(ruleArg["condition"]) then
                    return false;
                end
            end
        end

        return true;
    end

    for _, id in pairs(ids) do
        if isValidId(id) then
            -- 尝试完成成就
            AchievementM.tryComplete(id, 1);
        end
    end
end


-- 检查条件
function checkCondition(condition)
    if "pick_all_bottle" == condition then
        -- 拾取所有的漂流瓶

        if not DriftBottleM.isAllBottlePicked() then
            return false;
        end
    end

    if "pick_up_demon_coin" == condition then
        -- 投入妖精的钱币
        
        if not NewbieDungeonM.hasInputDemonCoin() then
            return false;
        end
    end
    
    return true;
end

return {

};